using AutoMapper;
using MediatR;
using Medical.Api.Write.Application.Command.BasicManagement.EquipmentPackageDictionaryCommand;
using Medical.Domain.BasicManagement;
using Medical.ErrorCode;
using Medical.Interstructrue.Base;

namespace Medical.Api.Write.Application.Handler.BasicManagement.EquipmentPackageDictionaryHandler
{
    /// <summary>
    /// 更新器械包处理器
    /// </summary>
    public class UpdateEquipmentPackageHandler : IRequestHandler<UpdateEquipmentPackageCommand, ApiResult<bool>>
    {
        private readonly IBaseRepository<EquipmentPackage> _packageRepository;
        private readonly ILogger<UpdateEquipmentPackageHandler> _logger;
        private readonly IMapper _mapper;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="packageRepository">仓储</param>
        /// <param name="logger">日志记录器</param>
        /// <param name="mapper">对象映射器</param>
        public UpdateEquipmentPackageHandler(
            IBaseRepository<EquipmentPackage> packageRepository,
            ILogger<UpdateEquipmentPackageHandler> logger,
            IMapper mapper)
        {
            _packageRepository = packageRepository;
            _logger = logger;
            _mapper = mapper;
        }

        /// <summary>
        /// 处理更新器械包请求
        /// </summary>
        /// <param name="request">更新命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>更新结果</returns>
        public Task<ApiResult<bool>> Handle(UpdateEquipmentPackageCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 查询器械包是否存在
                var existingPackage = _packageRepository.GetModel(request.PackageData.Id);
                if (existingPackage == null)
                {
                    return Task.FromResult(new ApiResult<bool>
                    {
                        Code = ApiEnums.NotFound,
                        Msg = "器械包不存在",
                        Data = false
                    });
                }

                // 保存当前状态和删除标记，以免被覆盖
                var currentStatus = existingPackage.Status;
                var currentIsDeleted = existingPackage.IsDeleted;
                var currentPackageCode = existingPackage.PackageCode;
                var currentBarcodes = existingPackage.Barcodes;

                // 使用AutoMapper更新实体属性
                _mapper.Map(request.PackageData, existingPackage);

                // 恢复不应修改的属性
                existingPackage.Status = currentStatus;
                existingPackage.IsDeleted = currentIsDeleted;
                existingPackage.PackageCode = currentPackageCode; // 保留原有编码
                existingPackage.Barcodes = currentBarcodes; // 保留原有条形码
                existingPackage.UpdateTime = DateTime.Now;

                // 执行更新
                var result = _packageRepository.Update(existingPackage) > 0;

                _logger.LogInformation("更新器械包 {Name}，ID: {Id}, 结果: {Result}",
                    existingPackage.PackageName, existingPackage.Id, result ? "成功" : "失败");

                return Task.FromResult(new ApiResult<bool>
                {
                    Code = result ? ApiEnums.Success : ApiEnums.Error,
                    Msg = result ? "更新成功" : "更新失败",
                    Data = result
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新器械包时发生异常");
                return Task.FromResult(new ApiResult<bool>
                {
                    Code = ApiEnums.Fail,
                    Msg = "更新失败：系统内部错误",
                    Data = false
                });
            }
        }
    }
}